import ReactDOM from "react-dom/client";
import { Provider } from "react-redux";
import store from "./store";
import { BrowserRouter } from "react-router-dom";
import { ConfigProvider } from "antd";
import zhCN from "antd/locale/zh_CN";
import "./assets/iconfont/iconfont.css";
import App from "./App";
import "./index.scss"; //全局样式
import AutoScorllTop from "./AutoTop";
import { configCache } from "./utils/configCache";
import { requestMonitor } from "./utils/requestMonitor";
import Cookies from 'js-cookie';
// 导入 Cookie polyfill，确保全局 Cookies 对象可用
import './utils/cookiePolyfill';

// 设置全局 Cookies 对象，解决第三方库依赖问题
(window as any).Cookies = Cookies;

console.log('🍪 全局 Cookies 对象已设置:', typeof (window as any).Cookies);

// 应用启动时清理过期缓存
configCache.clearExpiredCache();

// 全局拦截器 - 强制阻止频繁的配置请求并修复错误的API地址
const originalFetch = window.fetch;
let lastConfigRequest = 0;
const MIN_CONFIG_INTERVAL = 5000; // 减少到5秒，避免过于严格
const CORRECT_API_BASE = "http://47.121.193.239:9800";

// 检测各种错误的API地址模式
const isWrongApiUrl = (url: string): boolean => {
  console.log('🔍 检查URL:', url);
  
  // 检测发送到开发服务器9797端口的API请求
  if (url.includes(':9797/api/')) {
    console.log('🚨 发现错误的API URL (端口9797):', url);
    return true;
  }
  
  // 检测其他已知的错误地址
  const wrongPatterns = [
    'http://192.168.31.140:9798',
    'http://192.168.31.140:9797/api',
    'http://localhost:9797/api',
    'http://127.0.0.1:9797/api'
  ];
  
  for (const pattern of wrongPatterns) {
    if (url.includes(pattern)) {
      console.log('🚨 发现错误的API URL (匹配模式):', pattern, url);
      return true;
    }
  }
  
  return false;
};

const fixApiUrl = (url: string): string => {
  console.log('🔧 开始修复URL:', url);
  
  // 提取API路径部分
  const apiMatch = url.match(/\/api\/v1\/.*$/);
  if (apiMatch) {
    const apiPath = apiMatch[0];
    const newUrl = CORRECT_API_BASE + apiPath;
    console.log('✅ URL修复成功:', newUrl);
    return newUrl;
  }
  
  console.log('⚠️ 无法提取API路径，返回原URL:', url);
  return url;
};

window.fetch = function(input: RequestInfo | URL, init?: RequestInit): Promise<Response> {
  let url = typeof input === 'string' ? input : input.toString();
  const originalUrl = url;
  
  console.log('🌐 Fetch请求:', originalUrl);
  
  // 检测并修复错误的API地址
  if (isWrongApiUrl(url)) {
    const newUrl = fixApiUrl(url);
    console.warn(`🔧 修复错误的API地址: ${originalUrl} -> ${newUrl}`);
    requestMonitor.logApiUrlFix(originalUrl, newUrl);
    url = newUrl;
    input = url;
  }
  
  // 拦截 system/config 请求（减少限制强度）
  if (url.includes('/api/v1/system/config')) {
    const now = Date.now();
    if (now - lastConfigRequest < MIN_CONFIG_INTERVAL) {
      console.warn(`全局拦截器: 阻止频繁的 system/config 请求 (间隔: ${now - lastConfigRequest}ms)`);
      // 不完全拒绝，而是返回缓存或者等待短时间
      if (lastConfigRequest > 0) {
        return new Promise((resolve, reject) => {
          setTimeout(() => {
            lastConfigRequest = now;
            originalFetch.call(this, input, init).then(resolve).catch(reject);
          }, 1000);
        });
      }
    }
    lastConfigRequest = now;
    console.log('✅ 全局拦截器: 允许 system/config 请求到:', url);
  }
  
  return originalFetch.call(this, input, init);
};

// 添加调试信息
console.log('🌐 当前访问地址:', window.location.href);
console.log('🔧 API请求将被重定向到:', CORRECT_API_BASE);

// 测试URL重写功能
const testUrl = 'http://192.168.31.140:9797/api/v1/system/config';
console.log('🧪 测试URL重写:', testUrl, '->', fixApiUrl(testUrl));

ReactDOM.createRoot(document.getElementById("root") as HTMLElement).render(
  <Provider store={store}>
    <ConfigProvider
      locale={zhCN}
      theme={{ token: { colorPrimary: "#ff4d4f" } }}
    >
      <BrowserRouter>
        <AutoScorllTop>
          <App />
        </AutoScorllTop>
      </BrowserRouter>
    </ConfigProvider>
  </Provider>
);
